package com.mad.bikepony.service.persistence;

import java.util.List;

import com.liferay.portal.kernel.dao.orm.SQLQuery;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;
import com.mad.bikepony.model.Delivery;
import com.mad.bikepony.model.DeliveryState;
import com.mad.bikepony.model.impl.DeliveryImpl;

public class DeliveryFinderImpl extends BasePersistenceImpl<Delivery> implements DeliveryFinder{

	
	@SuppressWarnings("unchecked")
	public Delivery findLastPendingDeliveryForAgent(long agentId)
	{
		String sql ="select Delivery.* from bp_delivery as Delivery," +
				"(SELECT d1.estimatedPickupTime as ep,deliveryId as del1 from bp_delivery d1 where (state_=:STATE_TO_PICKUP OR state_=:STATE_BEING_DELIVERED) ORDER by estimatedPickupTime DESC limit 1)as pickup," +
				"(SELECT d2.estimatedDeliveryTime as ed,d2.deliveryId as del2 from bp_delivery d2 where (state_=:STATE_TO_PICKUP OR state_=:STATE_BEING_DELIVERED) ORDER by estimatedDeliveryTime DESC limit 1)as delivery " +
				"where (Delivery.deliveryId = pickup.del1 AND pickup.ep>delivery.ed) OR (Delivery.deliveryId = delivery.del2 and delivery.ed>pickup.ep) AND Delivery.agentId=:AGENT ";
		SQLQuery sqlQuery = openSession().createSQLQuery(sql);
		sqlQuery.addEntity("Delivery", DeliveryImpl.class);
		sqlQuery.setInteger("STATE_TO_PICKUP", DeliveryState.WAITING_FOR_PICKUP.toState());
		sqlQuery.setInteger("STATE_BEING_DELIVERED", DeliveryState.BEING_DELIVERED.toState());
		sqlQuery.setLong("AGENT", agentId);
		
		List<Delivery> result = (List<Delivery>)sqlQuery.list();
		if(result.size()==1)
		{
			return result.get(0);
		}else
		return null;
	}
}
